<template>
	<view class="comments-section">
		<view class="comments-header">
			<view class="header-title">亮回复 /{{ comments.length }}</view>
			<view class="header-tabs">
				<text class="tab-item" :class="{ active: sortType === 'hot' }" @tap="changeSort('hot')">最亮</text>
				<text class="tab-item" :class="{ active: sortType === 'latest' }" @tap="changeSort('latest')">最晚</text>
				<text class="tab-item" :class="{ active: sortType === 'oldest' }" @tap="changeSort('oldest')">最早</text>
			</view>
		</view>
		
		<!-- 评论列表 -->
		<view class="comments-list">
			<view class="comment-item" v-for="(comment, index) in sortedComments" :key="comment.id">
				<!-- 用户头像 -->
				<view class="comment-avatar">
					<image :src="comment.avatar" mode="aspectFill"></image>
				</view>
				
				<!-- 评论内容区 -->
				<view class="comment-body">
					<!-- 用户名 -->
					<view class="comment-user">{{ comment.username }}</view>
					
					<!-- 评论内容 -->
					<view class="comment-text">{{ comment.content }}</view>
					
					<!-- 评论底部信息 -->
					<view class="comment-footer">
						<view class="comment-info">
							<view class="comment-time">
								{{ comment.time_str }} {{ comment.location }} 
								<text class="reply-text" @tap="showQuickReplyInput(comment.username, -1, undefined, undefined, undefined, comment.id)">回复</text>
							</view>
						</view>
						<view class="comment-actions">
							<view class="action-like" @tap="likeComment(comment)">
								<uni-icons type="hand-up" size="18" :color="comment.isLiked ? '#ff6b6b' : '#999'"></uni-icons>
								<text :class="{'liked-text': comment.isLiked}">{{ comment.likes }}</text>
							</view>
							
							<view class="action-report">
								<uni-icons type="info" size="18" color="#999"></uni-icons>
							</view>
						</view>
					</view>
					
					<!-- 显示一条回复 -->
					<view class="first-reply-preview" v-if="comment.replies && comment.replies.length > 0">
						<view class="first-reply-content">
							<view class="first-reply-avatar">
								<image :src="comment.replies[0].avatar" mode="aspectFill"></image>
							</view>
							<view class="first-reply-body">
								<view class="first-reply-username">{{ comment.replies[0].username }}</view>
								<view class="first-reply-text">{{ comment.replies[0].content }}</view>
								<view class="first-reply-meta">
									<view class="first-reply-time">
										{{ comment.replies[0].time_str }} {{ comment.replies[0].location }}
										<text class="reply-text" @tap="showQuickReplyInput(comment.replies[0].username, -1, 0, undefined, undefined, comment.id)">回复</text>
									</view>
									<view class="first-reply-actions">
										<view class="first-reply-like" @tap="likeReply(comment.replies[0], index, 0)">
											<uni-icons type="hand-up" size="16" :color="comment.replies[0].isLiked ? '#ff6b6b' : '#999'"></uni-icons>
											<text :class="{'liked-text': comment.replies[0].isLiked}">{{ comment.replies[0].likes }}</text>
										</view>
										<view class="first-reply-report">
											<uni-icons type="info" size="16" color="#999"></uni-icons>
										</view>
									</view>
								</view>
							</view>
						</view>
						
						<!-- 查看更多回复按钮 -->
						<view class="view-replies" v-if="comment.replies.length > 1" @tap="showReplyPopup(comment, -1, comment.id)">
							<view class="view-replies-text">
								<text>查看{{ comment.replies.length - 1 }}条回复</text>
								<uni-icons type="right" size="14" color="#576b95"></uni-icons>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部评论输入区 -->
		<view class="comment-input-bar" v-if="!hideInputBar">
			<input class="comment-input" type="text" placeholder="打个友善的分，说句好听的话" v-model="commentText" confirm-type="send" @confirm="submitComment" />
			<view class="comment-actions">
				<view class="action-item">
					<uni-icons type="hand-up" size="24" color="#666" class="action-icon"></uni-icons>
					<text class="action-text">点赞</text>
				</view>
				<view class="action-item">
					<uni-icons type="chat" size="24" color="#666" class="action-icon"></uni-icons>
					<text class="action-text">1.0万</text>
				</view>
			</view>
		</view>
		
		<!-- 回复弹窗(蒙层) -->
		<view class="reply-popup-mask" v-if="showPopup" @tap="closePopup" @touchmove.stop.prevent>
			<view class="reply-popup" @tap.stop>
				<!-- 关闭按钮 -->
				<view class="reply-popup-header">
					<view class="popup-title">查看回复</view>
					<view class="popup-close" @tap="closePopup">×</view>
				</view>
				
				<!-- 主评论 -->
				<view class="main-comment">
					<view class="user-avatar-wrap">
						<image class="user-avatar" :src="currentComment.avatar"></image>
					</view>
					<view class="main-comment-content">
						<view class="main-user-name">{{ currentComment.username }}</view>
						<view class="main-comment-text">{{ currentComment.content }}</view>
						<view class="main-comment-meta">
							<view class="main-comment-time">
								{{ currentComment.time_str }} {{ currentComment.location }} 
								<text class="reply-text" @tap="showQuickReplyInput(currentComment.username, currentCommentIndex.value, undefined, undefined, undefined, currentComment.id)">回复</text>
							</view>
							<view class="main-comment-actions">
								<view class="main-like-btn" @tap="likeComment(currentComment)">
									<uni-icons type="hand-up" size="18" :color="currentComment.isLiked ? '#ff6b6b' : '#999'"></uni-icons>
									<text :class="{'liked-text': currentComment.isLiked}">{{ currentComment.likes }}</text>
								</view>
								<view class="main-report-btn">
									<uni-icons type="info" size="18" color="#999"></uni-icons>
								</view>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 分隔线 -->
				<view class="reply-divider"></view>
				
				<!-- 回复导航 -->
				<view class="reply-nav">
					<view class="reply-count">全部回复 /{{ currentComment.replies ? currentComment.replies.length : 0 }}</view>
					<view class="reply-sort-options">
						<text class="sort-option" :class="{ active: replySortType === 'hot' }" @tap="changeReplySort('hot')">最亮</text>
						<text class="sort-option" :class="{ active: replySortType === 'latest' }" @tap="changeReplySort('latest')">最晚</text>
						<text class="sort-option" :class="{ active: replySortType === 'oldest' }" @tap="changeReplySort('oldest')">最早</text>
					</view>
				</view>
				
				<!-- 回复列表 -->
				<scroll-view class="reply-list-scroll" scroll-y enable-flex="true" :style="{height: 'calc(70vh - 260rpx)'}" @touchmove.stop>
					<view class="reply-list-container">
						<view class="reply-item" v-for="(reply, replyIndex) in sortedReplies" :key="replyIndex">
							<view class="reply-user-avatar">
								<image :src="reply.avatar"></image>
							</view>
							<view class="reply-content-wrap">
								<view class="reply-username">{{ reply.username }}</view>
								<view class="reply-content-text">{{ reply.content }}</view>
								<view class="reply-meta">
									<view class="reply-time">
										{{ reply.time_str }} {{ reply.location }} 
										<text class="reply-text" @tap="showQuickReplyInput(reply.username, currentCommentIndex, replyIndex, null, null, currentComment.id)">回复</text>
									</view>
									<view class="reply-actions" @tap="likeReply(reply)">
										<uni-icons type="hand-up" size="18" :color="reply.isLiked ? '#ff6b6b' : '#999'"></uni-icons>
										<text :class="{'liked-text': reply.isLiked}">{{ reply.likes }}</text>
									</view>
								</view>
								
								<!-- 嵌套回复区域 -->
								<view class="nested-replies-area" v-if="reply && reply.moreReplies && reply.moreReplies.length > 0">
									<!-- 只显示第一条嵌套回复 -->
									<view class="nested-reply" v-if="reply && reply.moreReplies && reply.moreReplies[0]">
										<view class="nested-reply-avatar">
											<image :src="reply.moreReplies[0].avatar"></image>
										</view>
										<view class="nested-reply-content">
											<view class="nested-reply-username">{{ reply.moreReplies[0].username }}</view>
											<view class="nested-reply-text">
												<text v-if="reply.moreReplies[0].replyTo" class="reply-to-name">回复 <text class="blue-name">{{ reply.moreReplies[0].replyTo }}</text>：</text>
												<text>{{ reply.moreReplies[0].content }}</text>
											</view>
											<view class="nested-reply-meta">
												<view class="nested-reply-time">
													{{ reply.moreReplies[0].time_str }} {{ reply.moreReplies[0].location }} 
													<text class="reply-text" @tap="showQuickReplyInput(reply.moreReplies[0].username, currentCommentIndex, replyIndex, 'nested', 0, currentComment.id, reply.moreReplies[0].id)">回复</text>
												</view>
												<view class="nested-reply-actions">
													<uni-icons type="hand-up" size="16" color="#999"></uni-icons>
													<text>{{ reply.moreReplies[0].likes }}</text>
												</view>
											</view>
										</view>
									</view>
									
									<!-- 展开所有回复 -->
									<template v-if="reply && reply.showMoreReplies && reply.moreReplies && reply.moreReplies.length > 1">
										<view class="nested-reply" v-for="(nestedReply, nestedIndex) in reply.moreReplies.slice(1)" :key="nestedIndex">
											<view class="nested-reply-avatar">
												<image :src="nestedReply.avatar"></image>
											</view>
											<view class="nested-reply-content">
												<view class="nested-reply-username">{{ nestedReply.username }}</view>
												<view class="nested-reply-text">
													<text v-if="nestedReply.replyTo" class="reply-to-name">回复 <text class="blue-name">{{ nestedReply.replyTo }}</text>：</text>
													<text>{{ nestedReply.content }}</text>
													

												</view>
												<view class="nested-reply-meta">
													<view class="nested-reply-time">
														{{ nestedReply.time_str }} {{ nestedReply.location }} 
														<text class="reply-text" @tap="showQuickReplyInput(nestedReply.username, currentCommentIndex, replyIndex, 'nested', nestedIndex + 1, currentComment.id, nestedReply.id)">回复</text>
													</view>
													<view class="nested-reply-actions" @tap="likeNestedReply(reply, nestedReply)">
														<uni-icons type="hand-up" size="16" :color="nestedReply.isLiked ? '#ff6b6b' : '#999'"></uni-icons>
														<text :class="{'liked-text': nestedReply.isLiked}">{{ nestedReply.likes }}</text>
													</view>
												</view>
											</view>
	</view>
</template>

									<!-- 展开/收起按钮 -->
									<view class="expand-more-replies" v-if="reply && reply.moreReplies && reply.moreReplies.length > 1" @tap="toggleMoreReplies(reply)">
										<view class="expand-more-text">
											<text>{{ reply.showMoreReplies ? '收起回复' : '展开更多回复' }}</text>
											<uni-icons :type="reply.showMoreReplies ? 'top' : 'bottom'" size="14" color="#576b95"></uni-icons>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
				
				<!-- 底部输入框 -->
				<view class="reply-input-area">
					<input 
						style="width:100%;height:70rpx;background:#f5f5f5;border-radius:35rpx;padding:0 20rpx;box-sizing:border-box;" 
						type="text" 
						placeholder="灵魂只要有趣，文字才会沸腾" 
						confirm-type="send" 
						cursor-spacing="10"
						:focus="inputFocus"
						adjust-position
						v-model="replyText" 
						@confirm="sendReply"
						@blur="inputFocus = false"
					/>
				</view>
			</view>
		</view>
		
		<!-- 快速回复弹窗 -->
		<view class="quick-reply-popup" v-if="showQuickReply" @touchmove.stop.prevent>
			<view class="quick-reply-mask" @tap="closeQuickReply"></view>
			<view class="quick-reply-box">
				<view class="quick-reply-header">
					<text class="quick-reply-title">回复「{{ replyToUsername }}」</text>
					<text class="quick-reply-close" @tap="closeQuickReply">×</text>
				</view>
				<view class="quick-reply-content">
					<input 
						class="quick-reply-input"
						v-model="quickReplyText"
						focus
						placeholder="请输入回复内容"
						confirm-type="send"
						:adjust-position="true"
						:cursor-spacing="30"
						@confirm="submitQuickReply"
					/>
				</view>
				<view class="quick-reply-emoji">
					<view class="publish-button" @tap="submitQuickReply">发布</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed } from 'vue'

// 组件接收的属性
const props = defineProps({
	// 可以传入初始评论数据
	initialComments: {
		type: Array,
		default: () => []
	},
	// 是否隐藏底部输入框
	hideInputBar: {
		type: Boolean,
		default: false
	}
})

// 向父组件发送的事件
const emit = defineEmits(['comment-added', 'reply-added', 'like-changed'])

// 统一的logo头像
const logoAvatar = '/static/logo.png'

// 响应式状态
const commentText = ref('')  // 添加评论文本变量
const sortType = ref('hot')  // 排序方式：hot(最亮)、latest(最晚)、oldest(最早)、default(原始顺序)

// 评论数据
const comments = ref(props.initialComments.length > 0 ? props.initialComments : [
	{
		id: 1,
		username: '虎扑JR0910476578',
		avatar: logoAvatar,
		content: '有你下路二打一，野区被入成狗，完事还说队友坑',
		time_str: '2024-03-27',
		location: '广东',
		likes: 1629,
		isLiked: false,
		showReplies: false,
		replies: [
			{
				id: 101,
				username: '虎扑JR1455939544',
				avatar: logoAvatar,
				content: '你别说还挺押韵的',
				time_str: '2024-04-14',
				location: '四川',
				likes: 27,
				isLiked: false,
				hasMoreReplies: true,
				showMoreReplies: false,
				moreReplies: [
					{
						id: 1001,
						username: '振德食泥鸭',
						avatar: logoAvatar,
						content: '哈哈兄弟你这个我绷不住了',
						time_str: '2024-05-31',
						location: '河北',
						likes: 10,
						isLiked: false
					},
					{
						id: 1002,
						username: '虎扑JR0777692087',
						avatar: logoAvatar,
						content: '确实，不再嵌套，只显示三级',
						time_str: '2024-05-15',
						location: '北京',
						likes: 8,
						isLiked: false
					}
				]
			}
		]
	},
	{
		id: 2,
		username: '说事实别瞎想',
		avatar: logoAvatar,
		content: '听见"瑶瑶公主"四个字就直犯恶心',
		time_str: '2023-04-17',
		location: '',
		likes: 5969,
		isLiked: false,
		showReplies: false,
		replies: []
	}
])

// 获取时间戳的工具函数
const getTimestamp = (dateStr) => {
	if (!dateStr) return 0
	if (dateStr === '刚刚') return Date.now()
	try {
		return new Date(dateStr).getTime()
	} catch (e) {
		return 0
	}
}

// 递归处理评论数据，确保所有必要的属性都存在
const ensureCommentProperties = (comment) => {
	if (!comment) return
	
	// 确保基本属性存在
	if (!comment.replies) comment.replies = []
	if (!comment.moreReplies) comment.moreReplies = []
	
	// 处理回复
	comment.replies.forEach(reply => {
		if (!reply.moreReplies) reply.moreReplies = []
		if (reply.hasMoreReplies === undefined) reply.hasMoreReplies = reply.moreReplies.length > 0
		if (reply.showMoreReplies === undefined) reply.showMoreReplies = false
	})
}

// 排序后的评论
const sortedComments = computed(() => {
	const commentsCopy = [...comments.value]
	
	switch (sortType.value) {
		case 'hot':
			// 按点赞数排序
			return commentsCopy.sort((a, b) => b.likes - a.likes)
		case 'latest':
			// 按时间倒序（最新的在前）
			return commentsCopy.sort((a, b) => getTimestamp(b.time_str) - getTimestamp(a.time_str))
		case 'oldest':
			// 按时间顺序（最早的在前）
			return commentsCopy.sort((a, b) => getTimestamp(a.time_str) - getTimestamp(b.time_str))
		default:
			return commentsCopy
	}
})

// 更改排序方式
const changeSort = (type) => {
	sortType.value = type
}

// 根据评论ID查找原始评论索引
const findOriginalCommentIndex = (commentId) => {
	// 在原始评论数组中查找匹配ID的评论
	const index = comments.value.findIndex(c => c.id === commentId)
	console.log(`找到评论ID=${commentId}的原始索引:`, index)
	return index
}

// 弹窗状态
const showPopup = ref(false)
const currentComment = ref({})
const currentCommentIndex = ref(-1)
const replyText = ref('')
const inputFocus = ref(false)

// 回复排序变量
const replySortType = ref('hot')

// 排序后的回复
const sortedReplies = computed(() => {
	if (!currentComment.value || !currentComment.value.replies) return []
	
	const repliesCopy = [...currentComment.value.replies]
	
	switch (replySortType.value) {
		case 'hot':
			// 按点赞数排序
			return repliesCopy.sort((a, b) => b.likes - a.likes)
		case 'latest':
			// 按时间倒序（最新的在前）
			return repliesCopy.sort((a, b) => getTimestamp(b.time_str) - getTimestamp(a.time_str))
		case 'oldest':
			// 按时间顺序（最早的在前）
			return repliesCopy.sort((a, b) => getTimestamp(a.time_str) - getTimestamp(b.time_str))
		default:
			return repliesCopy
	}
})

// 更改回复排序方式
const changeReplySort = (type) => {
	replySortType.value = type
}

// 切换展开/收起更多回复
const toggleMoreReplies = (reply) => {
	if (!reply) {
		console.error('切换更多回复失败: reply对象为空')
		return
	}
	
	// 如果showMoreReplies属性不存在，先初始化为false
	if (reply.showMoreReplies === undefined) {
		reply.showMoreReplies = false
	}
	
	reply.showMoreReplies = !reply.showMoreReplies
}

// 记录滚动位置
const scrollPosition = ref(0)

// 显示回复弹窗
const showReplyPopup = (comment, index, commentId) => {
	// 获取当前页面滚动位置
	const query = uni.createSelectorQuery()
	query.selectViewport().scrollOffset(res => {
		scrollPosition.value = res.scrollTop
	}).exec()
	
	// 如果提供了commentId，找到对应的索引
	if (commentId) {
		index = comments.value.findIndex(c => c.id === commentId)
		console.log(`通过ID=${commentId}找到评论索引:`, index)
	}
	
	// 设置弹窗内容
	currentComment.value = comment
	currentCommentIndex.value = index
	showPopup.value = true
	
	// 不自动聚焦输入框
	inputFocus.value = false
}

// 关闭弹窗
const closePopup = () => {
	inputFocus.value = false
	setTimeout(() => {
		showPopup.value = false
		replyText.value = ''
		
		// 恢复滚动位置
		setTimeout(() => {
			uni.pageScrollTo({
				scrollTop: scrollPosition.value,
				duration: 0
			})
		}, 50)
	}, 100)
}

// 发送回复
const sendReply = () => {
	if (!replyText.value.trim()) return
	
	// 创建新回复
	const newReply = {
		id: Date.now(),
		username: '我',
		avatar: logoAvatar,
		content: replyText.value,
		time_str: '刚刚',
		location: '',
		likes: 0,
		isLiked: false,
		// 确保所有必要的属性都存在
		moreReplies: [],
		hasMoreReplies: false,
		showMoreReplies: false
	}
	
	// 添加到当前评论的回复列表
	if (currentCommentIndex.value >= 0 && comments.value[currentCommentIndex.value]) {
		if (!comments.value[currentCommentIndex.value].replies) {
			comments.value[currentCommentIndex.value].replies = []
		}
		
		comments.value[currentCommentIndex.value].replies.unshift(newReply)
		currentComment.value = comments.value[currentCommentIndex.value]
		
		// 向父组件发送回复添加事件
		emit('reply-added', newReply, currentCommentIndex.value)
	}
	
	// 清空输入
	replyText.value = ''
	inputFocus.value = false
	
	// 反馈
	uni.vibrateShort()
	uni.showToast({
		title: '回复成功',
		icon: 'none'
	})
}

// 添加提交评论功能
const submitComment = () => {
	if (!commentText.value.trim()) return
	
	// 创建新评论
	const newComment = {
		id: Date.now(),
		username: '我',
		avatar: logoAvatar,
		content: commentText.value,
		time_str: '刚刚',
		location: '',
		likes: 0,
		isLiked: false,
		showReplies: false,
		replies: [],
		// 确保所有必要的属性都存在
		hasMoreReplies: false,
		showMoreReplies: false
	}
	
	// 添加到评论列表
	comments.value.unshift(newComment)
	
	// 向父组件发送评论添加事件
	emit('comment-added', newComment)
	
	// 清空输入
	commentText.value = ''
	
	// 反馈
	uni.vibrateShort()
	uni.showToast({
		title: '评论成功',
		icon: 'none'
	})
}

// 快速回复相关状态
const showQuickReply = ref(false)
const replyToUsername = ref('')
const quickReplyText = ref('')
const currentReplyTarget = ref(null) // 存储当前回复的目标评论/回复
const lastScrollPosition = ref(0) // 记录最后的滚动位置

// 显示快速回复输入框
const showQuickReplyInput = (username, commentIndex, replyIndex, replyType, nestedIndex, commentId, nestedReplyId) => {
	// 将null值转换为undefined，确保一致性
	if (replyIndex === null) replyIndex = undefined
	if (replyType === null) replyType = undefined
	if (nestedIndex === null) nestedIndex = undefined
	// 记录当前页面滚动位置以便回复后返回
	const query = uni.createSelectorQuery()
	query.selectViewport().scrollOffset(res => {
		lastScrollPosition.value = res.scrollTop
	}).exec()
	
	// 如果提供了commentId，通过ID查找原始索引
	if (commentId) {
		commentIndex = comments.value.findIndex(c => c.id === commentId)
		console.log(`通过ID=${commentId}找到评论索引:`, commentIndex)
	}
	
	// 记录当前回复目标
	currentReplyTarget.value = {
		commentIndex: commentIndex,  // 评论的索引
		replyIndex: replyIndex,
		replyType: replyType, // 添加回复类型标识: undefined=回复主评论, normal=回复二级评论, nested=回复三级评论
		nestedIndex: nestedIndex, // 添加嵌套回复的索引
		commentId: commentId, // 保存评论ID方便后续使用
		nestedReplyId: nestedReplyId // 保存嵌套回复的ID，用于标识回复的是哪个三级回复
	}
	
			console.log('设置回复目标:', { 
		username, 
		commentIndex, 
		replyIndex, 
		replyType, 
		nestedIndex,
		commentId,
		nestedReplyId
	})
	
	replyToUsername.value = username
	showQuickReply.value = true
}

// 关闭快速回复
const closeQuickReply = () => {
	// 关闭弹窗
	showQuickReply.value = false
	quickReplyText.value = ''
	replyToUsername.value = ''
	
	// 恢复到之前的滚动位置
	setTimeout(() => {
		uni.pageScrollTo({
			scrollTop: lastScrollPosition.value,
			duration: 0
		})
	}, 50)
}

// 提交快速回复
const submitQuickReply = () => {
	// 首先检查当前回复目标是否有效
	if (!currentReplyTarget.value) {
		console.error('无效的回复目标')
		uni.showToast({
			title: '回复失败，请重试',
			icon: 'none'
		})
		return
	}
	if (!quickReplyText.value.trim()) return
	
	// 创建新回复
	let newReply = {
		id: Date.now(),
		username: '我',
		avatar: logoAvatar,
		content: quickReplyText.value,
		time_str: '刚刚',
		location: '',
		likes: 0,
		isLiked: false,
		// 确保所有必要的属性都存在
		moreReplies: [],
		hasMoreReplies: false, 
		showMoreReplies: false,
		responses: [] // 用于存储对这个评论的回复（四级回复）
	}
	
	// 添加replyTo标记来标识回复对象
	if (currentReplyTarget.value) {
		// 只有是回复三级评论时才添加replyTo标记
		// 二级评论回复不需要显示"回复XXX:"前缀
		if (currentReplyTarget.value.replyType === 'nested') {
			newReply.replyTo = replyToUsername.value
		}
	}
	
	// 添加到相应的评论/回复列表
	if (currentReplyTarget.value) {
		// 重要：获取目标索引时不要改变原始值
		let commentIndex = currentReplyTarget.value.commentIndex
		const replyIndex = currentReplyTarget.value.replyIndex
		const replyType = currentReplyTarget.value.replyType
		const nestedIndex = currentReplyTarget.value.nestedIndex
		const commentId = currentReplyTarget.value.commentId
		const nestedReplyId = currentReplyTarget.value.nestedReplyId
		
		// 如果有评论ID但索引无效，尝试再次通过ID查找
		if (commentId && (commentIndex === undefined || commentIndex < 0)) {
			commentIndex = comments.value.findIndex(c => c.id === commentId)
			console.log(`通过ID=${commentId}重新查找评论索引:`, commentIndex)
		}
		
		// 打印详细日志，便于调试
		console.log('回复目标详情:', { 
			commentIndex, 
			replyIndex, 
			replyType, 
			nestedIndex, 
			commentId,
			nestedReplyId,
			username: replyToUsername.value,
			commentLength: comments.value.length,
			target: currentReplyTarget.value
		})
		
		// 确保commentIndex有效
		if (commentIndex !== undefined && commentIndex >= 0 && commentIndex < comments.value.length) {
			// 情况1: 如果是回复主评论
			if (replyIndex === undefined || replyIndex === null) {
				// 确保有replies数组
				if (!comments.value[commentIndex].replies) {
					comments.value[commentIndex].replies = []
				}
				
				// 添加到该评论的回复列表末尾，使其显示在后面
				comments.value[commentIndex].replies.push(newReply)
				
				console.log(`已添加回复到评论[${commentIndex}]下，共${comments.value[commentIndex].replies.length}条回复`)
				
				// 如果当前评论正好是弹窗中显示的评论，也更新currentComment
				if (currentCommentIndex.value === commentIndex) {
					currentComment.value = comments.value[commentIndex]
				}
				
				// 向父组件发送回复添加事件
				emit('reply-added', newReply, commentIndex)
			} 
			// 情况2: 如果是回复二级评论或三级评论
			else if (replyIndex !== undefined && replyIndex !== null && replyIndex >= 0 && 
					 comments.value[commentIndex].replies && 
					 replyIndex < comments.value[commentIndex].replies.length) {
				
				// 给回复添加嵌套回复
				try {
					const targetReply = comments.value[commentIndex].replies[replyIndex]
					
					// 为防止目标回复不存在，添加安全检查
					if (!targetReply) {
						console.error(`在评论[${commentIndex}]下找不到索引为[${replyIndex}]的回复`)
						
						// 降级到评论回复
						if (!comments.value[commentIndex].replies) {
							comments.value[commentIndex].replies = []
						}
						
						// 添加到该评论的回复列表末尾，使其显示在后面
						comments.value[commentIndex].replies.push(newReply)
						return
					}
					
					// 确保回复对象有必要的嵌套回复属性
					if (!targetReply.moreReplies) {
						targetReply.moreReplies = []
					}
					
					if (targetReply.hasMoreReplies === undefined) {
						targetReply.hasMoreReplies = true
					}
					
					if (targetReply.showMoreReplies === undefined) {
						targetReply.showMoreReplies = true
					}
				} catch (e) {
					console.error('初始化嵌套回复失败:', e)
					
					// 降级到评论回复
					if (!comments.value[commentIndex].replies) {
						comments.value[commentIndex].replies = []
					}
					
					// 添加到该评论的回复列表末尾，使其显示在后面
					comments.value[commentIndex].replies.push(newReply)
					return
				}
				
				// 添加到嵌套回复中
				try {
					const targetReply = comments.value[commentIndex].replies[replyIndex]
					if (targetReply && targetReply.moreReplies) {
						// 无论是回复三级评论还是二级评论，都添加到同一级别
						// 确保在回复三级评论时显示"回复XXX:"前缀
						if (replyType === 'nested' && nestedReplyId) {
							// 找到对应的三级评论以获取用户名
							const targetNestedReply = targetReply.moreReplies.find(r => r.id === nestedReplyId);
							if (targetNestedReply) {
								// 确保replyTo字段存在，这样可以显示前缀
								newReply.replyTo = targetNestedReply.username;
								console.log(`设置回复目标用户名: ${targetNestedReply.username}`);
							}
						}
						
						// 所有回复都添加到同一个数组中
						targetReply.moreReplies.push(newReply);
						console.log(`已添加嵌套回复到评论[${commentIndex}]的回复[${replyIndex}]下`);
						
						// 自动展开嵌套回复
						targetReply.showMoreReplies = true
					} else {
						console.error('无法添加嵌套回复，目标回复对象缺少必要属性')
						// 降级为评论回复
						if (!comments.value[commentIndex].replies) {
							comments.value[commentIndex].replies = []
						}
						comments.value[commentIndex].replies.push(newReply)
					}
				} catch (e) {
					console.error('添加嵌套回复失败:', e)
					// 降级为评论回复
					if (!comments.value[commentIndex].replies) {
						comments.value[commentIndex].replies = []
					}
					comments.value[commentIndex].replies.push(newReply)
				}
				
				// 如果当前评论正好是弹窗中显示的评论，也更新currentComment
				if (currentCommentIndex.value === commentIndex) {
					currentComment.value = comments.value[commentIndex]
				}
				
				// 向父组件发送嵌套回复添加事件
				emit('reply-added', newReply, commentIndex, replyIndex)
			}
			// 回复索引无效，但评论索引有效，添加到该评论下
			else {
				// 确保有replies数组
				if (!comments.value[commentIndex].replies) {
					comments.value[commentIndex].replies = []
				}
				
				// 添加到该评论的回复列表末尾，使其显示在后面
				comments.value[commentIndex].replies.push(newReply)
				
				console.log(`回复索引无效，已添加回复到评论[${commentIndex}]下`)
				
				// 如果当前评论正好是弹窗中显示的评论，也更新currentComment
				if (currentCommentIndex.value === commentIndex) {
					currentComment.value = comments.value[commentIndex]
				}
				
				// 向父组件发送回复添加事件
				emit('reply-added', newReply, commentIndex)
			}
		}
		// 评论索引无效，则在控制台输出错误
		else {
			console.error('评论索引无效:', commentIndex, '类型:', typeof commentIndex)
			// 检查索引是否超出范围
			if (commentIndex !== undefined && typeof commentIndex === 'number') {
				console.log('评论数组长度:', comments.value.length)
				if (commentIndex >= comments.value.length) {
					console.error('索引超出范围，最大索引应为:', comments.value.length - 1)
				}
			}
			uni.showToast({
				title: '回复失败，请重试',
				icon: 'none'
			})
			return
		}
	} 
	// 如果没有目标信息，显示错误提示
	else {
		console.error('没有回复目标信息')
		uni.showToast({
			title: '回复失败，请重试',
			icon: 'none'
		})
		return
	}
	
	// 提示成功
	uni.showToast({
		title: '回复成功',
		icon: 'none'
	})
	
	// 关闭弹窗并返回原位置
	showQuickReply.value = false
	quickReplyText.value = ''
	
	// 延迟一点关闭，确保页面已更新
	setTimeout(() => {
		// 查找刚刚添加的回复所在的评论位置
		if (currentReplyTarget.value && currentReplyTarget.value.commentIndex !== undefined) {
			// 获取评论元素的位置
			const commentIndex = currentReplyTarget.value.commentIndex;
			const query = uni.createSelectorQuery();
			
			// 检测最近添加的回复的父评论元素
			query.selectAll('.comment-item').boundingClientRect(rects => {
				if (rects && rects[commentIndex]) {
					// 滚动到该评论位置
					uni.pageScrollTo({
						scrollTop: rects[commentIndex].top,
						duration: 300
					})
					console.log('滚动到新回复位置:', rects[commentIndex].top);
				} else {
					// 如果找不到元素，才恢复到原来位置
					uni.pageScrollTo({
						scrollTop: lastScrollPosition.value,
						duration: 0
					})
					console.log('未找到元素，恢复到原始位置:', lastScrollPosition.value);
				}
			}).exec();
		} else {
			// 没有目标信息，恢复原始位置
			uni.pageScrollTo({
				scrollTop: lastScrollPosition.value,
				duration: 0
			})
			console.log('无回复目标，恢复原始位置:', lastScrollPosition.value);
		}
		
		// 清空用户名
		replyToUsername.value = ''
	}, 200)
	
	// 提供振动反馈
	uni.vibrateShort()
}

// 添加点赞功能函数
// 点赞评论
const likeComment = (comment) => {
	if (!comment.isLiked) {
		comment.likes += 1
		comment.isLiked = true
	} else {
		comment.likes -= 1
		comment.isLiked = false
	}
	
	// 提供点赞反馈
	uni.vibrateShort()
	
	// 向父组件发送点赞变化事件
	emit('like-changed', comment)
}

// 点赞回复
const likeReply = (reply, commentIndex, replyIndex) => {
	// 安全检查，确保参数存在
	if (!reply) {
		console.error('点赞回复参数无效:', { reply, commentIndex, replyIndex })
		return
	}
	
	if (!reply.isLiked) {
		reply.likes += 1
		reply.isLiked = true
	} else {
		reply.likes -= 1
		reply.isLiked = false
	}
	
	// 如果提供了评论索引，也更新currentComment中的数据
	if (commentIndex !== undefined && replyIndex !== undefined && 
			currentCommentIndex.value === commentIndex) {
		currentComment.value.replies[replyIndex] = reply
	}
	
	// 提供点赞反馈
	uni.vibrateShort()
	
	// 向父组件发送点赞变化事件
	emit('like-changed', reply, commentIndex, replyIndex)
}

// 点赞嵌套回复
const likeNestedReply = (parentReply, nestedReply) => {
	// 安全检查，确保参数存在
	if (!parentReply || !nestedReply) {
		console.error('点赞嵌套回复参数无效:', { parentReply, nestedReply })
		return
	}
	
	if (!nestedReply.isLiked) {
		nestedReply.likes += 1
		nestedReply.isLiked = true
	} else {
		nestedReply.likes -= 1
		nestedReply.isLiked = false
	}
	
	// 提供点赞反馈
	uni.vibrateShort()
}

// 导出部分方法以便父组件调用
defineExpose({
	addComment: (comment) => {
		comments.value.unshift(comment)
	},
	addReply: (reply, commentIndex) => {
		if (commentIndex >= 0 && commentIndex < comments.value.length) {
			if (!comments.value[commentIndex].replies) {
				comments.value[commentIndex].replies = []
			}
			comments.value[commentIndex].replies.unshift(reply)
		}
	},
	getComments: () => comments.value
})
</script>

<style lang="scss">
/* 全局变量 */
$primary-color: #336699;
$text-color: #333333;
$light-text: #999999;
$bg-color: #f5f5f5;
$border-color: #eeeeee;

/* 评论区域 */
.comments-section {
	background-color: #fff;
}

/* 首条回复预览样式 */
.first-reply-preview {
	margin-top: 16rpx;
	border-top: 1px solid #f5f5f5;
	padding-top: 16rpx;
}

.first-reply-content {
	display: flex;
	margin-bottom: 10rpx;
}

.first-reply-avatar {
	width: 60rpx;
	height: 60rpx;
	margin-right: 16rpx;
}

.first-reply-avatar image {
	width: 100%;
	height: 100%;
	border-radius: 50%;
}

.first-reply-body {
	flex: 1;
}

.first-reply-username {
	font-size: 28rpx;
	color: #576b95;
	margin-bottom: 8rpx;
}

.first-reply-text {
	font-size: 30rpx;
	color: #333;
	line-height: 1.5;
	margin-bottom: 8rpx;
}

.first-reply-meta {
	display: flex;
	justify-content: space-between;
}

.first-reply-time {
	font-size: 24rpx;
	color: #999;
}

.first-reply-actions {
	display: flex;
	align-items: center;
}

.first-reply-like, .first-reply-report {
	display: flex;
	align-items: center;
	margin-left: 20rpx;
}

.first-reply-like text, .first-reply-report text {
	font-size: 24rpx;
	color: #999;
	margin-left: 4rpx;
}

.liked-text {
	color: #ff6b6b !important;
}

.comments-header {
	display: flex;
	justify-content: space-between;
	padding: 30rpx;
	border-bottom: 1rpx solid $border-color;
}

.header-title {
	font-size: 34rpx;
	font-weight: bold;
	color: $text-color;
}

.header-tabs {
	display: flex;
}

.tab-item {
	font-size: 28rpx;
	color: $light-text;
	margin-left: 30rpx;
	
	&.active {
		color: $text-color;
	}
}

/* 评论列表 */
.comments-list {
	padding: 0 30rpx;
}

.comment-item {
	display: flex;
	padding: 30rpx 0;
	border-bottom: 1rpx solid $border-color;
}

.comment-avatar {
	width: 80rpx;
	height: 80rpx;
	margin-right: 20rpx;
	
	image {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}
}

.comment-body {
	flex: 1;
}

.comment-user {
	font-size: 30rpx;
	color: #576b95;
	margin-bottom: 10rpx;
}

.comment-text {
	font-size: 32rpx;
	line-height: 1.5;
	color: $text-color;
	margin-bottom: 15rpx;
}

.comment-footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10rpx;
}

.comment-info {
	font-size: 24rpx;
	color: $light-text;
}

.comment-actions {
	display: flex;
	align-items: center;
}

.action-like, .action-reply, .action-report {
	display: flex;
	align-items: center;
	margin-right: 30rpx;
	
	text {
		font-size: 26rpx;
		color: $light-text;
		margin-left: 4rpx;
	}
}

.view-replies {
	margin-top: 16rpx;
	
	.view-replies-text {
		font-size: 28rpx;
		color: #576b95;
		display: flex;
		align-items: center;
		
		text {
			margin-right: 4rpx;
		}
	}
}

/* 底部输入区域 */
.comment-input-bar {
	background-color: #fff;
	border-top: 1rpx solid #eee;
	padding: 12rpx 20rpx;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	width: 100%;
	z-index: 99;
	box-sizing: border-box;
	display: flex;
	align-items: center;
}

.comment-input {
	flex: 1;
	height: 70rpx;
	background-color: #f8f8f8;
	border-radius: 35rpx;
	color: #333;
	font-size: 28rpx;
	padding: 0 30rpx;
	margin-right: 20rpx;
}

.comment-actions {
	display: flex;
	align-items: center;
}

.action-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 0 15rpx;
	
	.action-icon {
		margin-bottom: 5rpx;
	}
	
	.action-text {
		font-size: 22rpx;
		color: #666;
	}
}

/* 回复弹窗 */
.reply-popup-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 999;
	display: flex;
	justify-content: center;
	align-items: center;
	touch-action: none; /* 防止触摸事件引起页面滚动 */
}

.reply-popup {
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	max-height: 90vh;
	background: #fff;
	border-radius: 24rpx 24rpx 0 0;
	overflow: hidden;
	display: flex;
	flex-direction: column;
	touch-action: manipulation; /* 允许在元素内部进行滚动和缩放 */
	animation: slideUp 0.3s ease;
}

@keyframes slideUp {
	from {
		transform: translateY(100%);
	}
	to {
		transform: translateY(0);
	}
}

/* 弹窗头部 */
.reply-popup-header {
	position: relative;
	height: 100rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	border-bottom: 1rpx solid #eee;
}

.popup-title {
	font-size: 34rpx;
	font-weight: 500;
	color: #333;
}

.popup-close {
	position: absolute;
	right: 30rpx;
	top: 50%;
	transform: translateY(-50%);
	font-size: 48rpx;
	color: #999;
	line-height: 1;
}

/* 主评论样式 */
.main-comment {
	padding: 30rpx;
	border-bottom: 1rpx solid #eee;
	display: flex;
}

.user-avatar-wrap {
	margin-right: 20rpx;
}

.user-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
}

.main-comment-content {
	flex: 1;
}

.main-user-name {
	font-size: 32rpx;
	color: #576b95;
	margin-bottom: 10rpx;
}

.main-comment-text {
	font-size: 34rpx;
	color: #333;
	line-height: 1.5;
	margin-bottom: 16rpx;
}

.main-comment-meta {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.main-comment-time {
	font-size: 26rpx;
	color: #999;
}

.reply-text {
	color: #336699;
	font-weight: 500;
	display: inline-block;
}

.main-comment-actions {
	display: flex;
	align-items: center;
}

.main-like-btn {
	display: flex;
	align-items: center;
	margin-right: 20rpx;
	
	text {
		font-size: 26rpx;
		color: #999;
		margin-left: 4rpx;
	}
}

.main-report-btn {
	display: flex;
	align-items: center;
}

/* 分隔线 */
.reply-divider {
	height: 20rpx;
	background-color: #f5f5f5;
}

/* 回复导航 */
.reply-nav {
	display: flex;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid #eee;
}

.reply-count {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}

.reply-sort-options {
	display: flex;
}

.sort-option {
	font-size: 28rpx;
	color: #999;
	margin-left: 20rpx;
	
	&.active {
		color: #333;
	}
}

/* 回复列表 */
.reply-list-scroll {
	flex: 1;
	background-color: #fff;
	overflow-y: auto; /* 确保垂直滚动只发生在这个元素内部 */
	-webkit-overflow-scrolling: touch; /* 增强iOS上的滚动体验 */
	position: relative;
	z-index: 1000; /* 确保滚动区域在最上层 */
}

.reply-list-container {
	padding-bottom: 100rpx;
}

.reply-item {
	display: flex;
	padding: 30rpx;
	border-bottom: 1rpx solid #eee;
}

.reply-user-avatar {
	width: 70rpx;
	height: 70rpx;
	margin-right: 20rpx;
	
	image {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}
}

.reply-content-wrap {
	flex: 1;
}

.reply-username {
	font-size: 30rpx;
	color: #576b95;
	margin-bottom: 10rpx;
}

.reply-content-text {
	font-size: 32rpx;
	color: #333;
	line-height: 1.5;
	margin-bottom: 16rpx;
}

.reply-meta {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16rpx;
}

.reply-time {
	font-size: 26rpx;
	color: #999;
}

.reply-actions {
	display: flex;
	align-items: center;
}

.reply-actions text {
	font-size: 26rpx;
	color: #999;
	margin-left: 4rpx;
}

/* 嵌套回复区 */
.nested-replies-area {
	background-color: #f8f8f8;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-top: 10rpx;
}

.nested-reply {
	display: flex;
	margin-bottom: 20rpx;
	
	&:last-child {
		margin-bottom: 0;
	}
}

.nested-reply-avatar {
	width: 60rpx;
	height: 60rpx;
	margin-right: 16rpx;
	
	image {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}
}

.nested-reply-content {
	flex: 1;
}

.nested-reply-username {
	font-size: 28rpx;
	color: #576b95;
	margin-bottom: 8rpx;
}

.nested-reply-text {
	font-size: 30rpx;
	color: #333;
	line-height: 1.5;
	margin-bottom: 10rpx;
	
	.reply-to-name {
		color: #333;
		font-weight: 500;
	}
	
	.blue-name {
		color: #576b95;
		font-weight: 500;
	}
}

.nested-reply-meta {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.nested-reply-time {
	font-size: 24rpx;
	color: #999;
}

.nested-reply-actions {
	display: flex;
	align-items: center;
	
	text {
		font-size: 24rpx;
		color: #999;
		margin-left: 4rpx;
	}
}

.expand-more-replies {
	margin-top: 16rpx;
	text-align: center;
	
	.expand-more-text {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		
		text {
			font-size: 28rpx;
			color: #576b95;
			margin-right: 4rpx;
		}
	}
}

/* 底部输入框 */
.reply-input-area {
	padding: 15rpx;
	background: #fff;
	border-top: 1px solid #eee;
	width: 100%;
	box-sizing: border-box;
	position: relative;
	z-index: 1001;
}

.reply-input {
	display: none;
}

/* 快速回复弹窗 */
.quick-reply-popup {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 999;
}

.quick-reply-mask {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
}

.quick-reply-box {
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	width: 100%;
	overflow: hidden;
	animation: slideUp 0.3s ease;
}

.quick-reply-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx;
	border-bottom: 1rpx solid #eee;
	background-color: #f8f8f8;
}

.quick-reply-title {
	font-size: 28rpx;
	color: #333;
	font-weight: normal;
}

.quick-reply-close {
	font-size: 36rpx;
	color: #999;
	line-height: 1;
}

.quick-reply-content {
	padding: 20rpx;
	background-color: #f8f8f8;
	height: 120rpx;
}

.quick-reply-input {
	width: 100%;
	height: 100%;
	background-color: #f8f8f8;
	border: none;
	font-size: 28rpx;
	color: #333;
}

.quick-reply-emoji {
	padding: 20rpx;
	background-color: #f8f8f8;
	display: flex;
	justify-content: flex-end;
	align-items: center;
	border-top: 1rpx solid #eee;
}

.publish-button {
	background-color: #c7c7cc;
	color: #fff;
	text-align: center;
	padding: 8rpx 20rpx;
	border-radius: 4rpx;
	font-size: 26rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.fourth-level-replies {
	margin-top: 10rpx;
	padding-top: 10rpx;
	border-top: 1px dashed #eee;
}

.fourth-level-reply {
	display: flex;
	margin-top: 15rpx;
	padding: 10rpx;
	background-color: #f9f9f9;
	border-radius: 8rpx;
}

.fourth-level-reply-avatar {
	width: 50rpx;
	height: 50rpx;
	margin-right: 10rpx;
}

.fourth-level-reply-avatar image {
	width: 100%;
	height: 100%;
	border-radius: 50%;
}

.fourth-level-reply-content {
	flex: 1;
}

.fourth-level-reply-username {
	font-size: 24rpx;
	color: #576b95;
	margin-bottom: 5rpx;
}

.fourth-level-reply-text {
	font-size: 24rpx;
	color: #333;
	line-height: 1.3;
	margin-bottom: 5rpx;
}

.fourth-level-reply-meta {
	font-size: 22rpx;
	color: #999;
}
</style>